﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.Model.Enums;
using SqlSugar;
using SqlSugar.IOC;

namespace Domain.Repository.Sugar
{
    public static class SugarDao
    {
        private static readonly ConcurrentDictionary<string, SqlSugarScope?> DbDictionary = new();
        private static readonly object Locker = new();
        /// <summary>
        /// 新建sqlsugar操作对象
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static SqlSugarScope? CreateSugarScope(string connectionString)
        {
            if (!DbDictionary.TryGetValue(connectionString, out SqlSugarScope? db))
            {
                lock (Locker)
                {
                    if (!DbDictionary.TryGetValue(connectionString, out db))
                    {
                        db = new SqlSugarScope(new ConnectionConfig
                        {
                            DbType = SqlSugar.DbType.SqlServer,
                            InitKeyType = InitKeyType.Attribute,
                            IsAutoCloseConnection = true,
                            ConnectionString = connectionString,
                            MoreSettings = new ConnMoreSettings()
                            {
                                IsWithNoLockQuery = true,
                            },
                        }, d =>
                            d.Aop.OnLogExecuting = (sql, pars) =>
                            {
                                Console.WriteLine(@$"SQL记录：{sql}SQL参数：{d.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}");
                                Console.WriteLine();
                            }
                        );
                        DbDictionary.TryAdd(connectionString, db);
                    }
                }
            }

            return db;

        }
        /// <summary>
        /// 从已注入的对象中获取sqlsugar操作对象
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static SqlSugarProvider GetInstance(EnumDbType db)
        {
            return DbScoped.SugarScope.GetConnection(db.ToString());
        }
    }
}